// components/classic/music/index.js
import {classicBeh} from '../classic-beh.js'
//获取音乐播放实例
const musicPlayer = wx.getBackgroundAudioManager()

Component({
  /**
   * 组件的属性列表
   * 
   */
  behaviors: [classicBeh],
  properties: {
    musicSrc:String,
    title:String
  },

  /**
   * 组件的初始数据
   */
  data: {
      playing:false,
      playSrc:'images/playing.png',
     pauseSrc:'images/stop-play.png',
     musicImg:'images/music.png'

  },
  //生命周期函数--最好不要在生命周期函数中直接添加过多的逻辑代码
  attached:function(){
   this._recoverMusic()
   this._monitorSwitch()
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onPlay:function(){
     if(!this.data.playing){
       this.setData({
         playing:true
       })
       musicPlayer.src = this.properties.musicSrc
       musicPlayer.title=this.properties.title
     }else{
       this.setData({
         playing: false
       })
       musicPlayer.pause()
     }
    },
    //设置音乐切换状态
    _recoverMusic:function(){
      //当前没有音乐播放
      if(musicPlayer.paused){
        this.setData({
          playing:false
        })
        return
      }
      else{
        //如果当前播放的音乐就是切换到的音乐
        if (musicPlayer.src == this.properties.musicSrc) {
          this.setData({
            playing: true
          })

        }
     
      }
    },
    //处理小程序自带音频播放与组件播放状态不同步问题
    _monitorSwitch:function(){
      //播放
      musicPlayer.onPlay(()=>{
        this._recoverMusic()
      })
      //暂停
      musicPlayer.onPause(()=>{
        this._recoverMusic()
      })
      //关闭：即点击‘x’
      musicPlayer.onStop(()=>{
        this._recoverMusic()
      })
      //歌曲自然播放结束
      musicPlayer.onEnded(()=>{
        this._recoverMusic()
      })
    }

  }
})
